﻿using IMES.Common.Domain.DariusModel;
using IMES.Common.Dtos;
using IMES.Common.Infrastructure;
using MediatR;
using Mysqlx.Crud;

namespace Darius.API.Application.Commands.Approval
{
    public class ApprovalCreateHandler : IRequestHandler<ApprovalCreateCommand, Result>
    {
        private readonly IBaseRepositorys<Approvals> approvalrepository;//审批表
        private readonly IBaseRepositorys<ApprovalApplications> approvalapplications;//审批流程表
        private readonly IBaseRepositorys<ApprovalProcess> approvalprocess;//审批申请表

        public ApprovalCreateHandler(IBaseRepositorys<Approvals> approvalrepository, IBaseRepositorys<ApprovalApplications> approvalapplications, IBaseRepositorys<ApprovalProcess> approvalprocess)
        {
            this.approvalrepository = approvalrepository;
            this.approvalapplications = approvalapplications;
            this.approvalprocess = approvalprocess;
        }
        /// <summary>
        /// 创建审批申请
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<Result> Handle(ApprovalCreateCommand request, CancellationToken cancellationToken)
        {
            var result = new Result() { Code = (int)CodeEnum.add };
            var res = 0;
            var approvalApplication = new ApprovalApplications()
            {
                ApprovalApplicationId = request.ApprovalApplicationId,
                SubmitlDate = request.SubmitlDate,
                SubmitName = request.SubmitName,
                SubmitEventId = request.SubmitEventId,
                OrderId = request.OrderId,
            };
            res += approvalapplications.Add(approvalApplication);
            foreach (var item in request.ApprovalsDto)
            {
                //获取倒序第一条数据
                var id1 = approvalapplications.GetAll().OrderByDescending(x => x.ApprovalApplicationId).ToList();
                //获取第一条数据的主键
                var id = id1.First().ApprovalApplicationId;
                //获取审批流程
                var approvalProcess = approvalprocess.GetAll().Where(x => x.ApprovalProcessId == 1).FirstOrDefault();
                //获取审批流程的审批人
                var approvalPersons = approvalProcess.Approvalers.Split(',');
                
                for (int i = 0; i < approvalPersons.Length; i++)
                {
                    var approval = new Approvals()
                    {
                        ApprovalApplicationId=id,
                        Approvaler=approvalPersons[i],

                    };
                   res += approvalrepository.Add(approval);
                } 
            }
            result.Messege = "等待审批";
            result.Code = res;
            return result;
        }
    }
}
